<template>
  <div>
    <!-- 面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片试图区域-->
    <el-card>
      <!--搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="15">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>

      <!--用户列表区域-->
      <el-table :data="userList" border stripe>
        <el-table-column  label="ID" prop="id"></el-table-column>
        <el-table-column label="姓名" prop="wxName"></el-table-column>
        <el-table-column label="电话" prop="wxPhone"></el-table-column>
        <el-table-column label="头像" >
          <template slot-scope="scope">
            <el-image
             style="width: 100px; height: 100px"
            :src="scope.row.headImage"
            :fit="fit"></el-image>
        </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="createTime"></el-table-column>
        <el-table-column label="OpenId" prop="userOpenid"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="success"
              round="true"
              size="mini"
              @click="updatePer(scope.row.id)"
            >分配权限</el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              round="true"
              size="mini"
              	
              @click="updateRole(scope.row.id)"
            >编辑角色</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

 
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='role'?'编辑角色':'编辑权限'"  @close="dialogClose">
      <el-form  label-width="80px" label-position="left">
        <el-form-item label="权限">
          <el-tree
              ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :default-checked-keys="checked"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" @click="confirmRole()">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getUser,updateRoleById,updatePermissionById} from '@/api/user'
import { getRoutes, getRoles ,getRoleByUserId,getPermissionByUserId} from '@/api/role'
export default {
  data() {
    // 校验邮箱
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 校验手机号
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示的条数
        pagesize: 2
      },
      userList: [],
      total: 0,
      dataVo:{},
      dialogVisible: false,
      dialogType: '',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'permissionName'
      },
      checked:[],
      routes: [],
      // 添加表单验证规则对象
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3-10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '密码的长度在6-15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      editForm: {},
      // 修改表单验证对象
      editFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const   res  = await getUser(this.queryInfo.query,this.queryInfo.pagenum,this.queryInfo.pagesize)
      console.log("user:"+res)
      this.userList = res.data.userList
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
      console.log(newSize)
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
      console.log(newPage)
    },
    // 修改用户状态
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 监听添加用户对话框的关闭事件
    async addDialogClosed() {
      // 重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 修改权限
    async updatePer(id) {
      this.dialogVisible=true
      this.dialogType='permission'
      this.dataVo.id=id
      const res = await getRoutes()
      this.routes = res.data
      this.defaultProps.label='permissionName'
      const rsp=  await getPermissionByUserId(id)

      this.checked=rsp.data

      this.$nextTick(() => {
          this.checkStrictly = false
      })
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(this.meta.msg)
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新成功')
      })
    },
    // 修改角色
    async updateRole(id) {
      this.dialogVisible=true
      this.dialogType='role'
      this.dataVo.id=id
      const {data} = await getRoles()
      this.routes = data
      this.defaultProps.label='roleName'
      const rsp=  await getRoleByUserId(id)

      this.checked=rsp.data
      
      this.$nextTick(() => {
          this.checkStrictly = false
      })
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'role'
      if (isEdit) {
        const checkedKeys = this.$refs.tree.getCheckedKeys()
           console.log("选择的id:"+checkedKeys)
           this.dataVo.roles=checkedKeys
        await updateRoleById(this.dataVo.id, this.dataVo)
      } else {
        const checkedKeys = this.$refs.tree.getCheckedKeys()
           console.log("选择的id:"+checkedKeys)
           this.dataVo.permissions=checkedKeys
           await updatePermissionById(this.dataVo.id,this.dataVo)
      }

      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
            <div>修改成功</div>
          `,
        type: 'success'
      })
    },
    dialogClose(){
      this.$nextTick(() => {

this.$refs.tree.setCheckedKeys([]);
});
    }
  }
}
</script>

<style lang="less" scoped></style>

